<template>
  <view class="custom-tab-bar">
    <view
      v-for="(item, index) in tabList"
      :key="index"
      class="tab-item"
      :class="{ active: current === index }"
      @tap="switchTab(item.pagePath, index)"
    >
      <image :src="current === index ? item.selectedIconPath : item.iconPath" />
      <text>{{ item.text }}</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'

const current = ref(0)
const tabList = [
  {
    pagePath: '/pages/index/index',
    iconPath: '/static/tabbar/home.png',
    selectedIconPath: '/static/tabbar/homeHL.png',
    text: '首页',
  },
  {
    pagePath: '/pages/scan/index',
    iconPath: '/static/tabbar/home.png',
    selectedIconPath: '/static/tabbar/homeHL.png',
    text: '扫码',
  },
  {
    pagePath: '/pages/about/about',
    iconPath: '/static/tabbar/example.png',
    selectedIconPath: '/static/tabbar/exampleHL.png',
    text: '关于',
  },
]

const switchTab = (path: string, index: number) => {
  if (current.value === index) return
  current.value = index
  uni.switchTab({
    url: path,
  })
}

onMounted(() => {
  console.log('tabbar mounted')
})

onShow(() => {
  console.log('tabbar shown')
  const pages = getCurrentPages()
  console.log('current pages:', pages)
  const page = pages[pages.length - 1]
  const path = `/${page.route}`
  const index = tabList.findIndex((item) => item.pagePath === path)
  if (index > -1) {
    current.value = index
  }
})
</script>

<style lang="scss" scoped>
.custom-tab-bar {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 999;
  display: flex;
  height: 50px;
  padding-bottom: env(safe-area-inset-bottom);
  background: #fff;
  box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);

  .tab-item {
    display: flex;
    flex: 1;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: 10px;
    color: #999;

    &.active {
      color: #018d71;
    }

    image {
      width: 24px;
      height: 24px;
      margin-bottom: 3px;
    }
  }
}
</style>
